--- interact_link: content/08/04/plotly8-4.ipynb kernel_name: python3 kernel_path: content/08/04 has_widgets: false title: |- Line Charts pagenum: 17 prev_page: url: /08/03/plotly8-3.html next_page: url: /08/05/plotly8-5.html suffix: .ipynb search: line id charts data chart plotlylinecharts plot ly python plots good changes want clearly display relationships continuous plotlylinechartsbasic basic plotlylinechartsmultiple multiple adding traces comment: "***PROGRAMMATICALLY GENERATED, DO NOT EDIT. SEE ORIGINAL FILES IN /content***" ---
Line Charts

Line Charts

Line Plots are good to use:

  • When data changes over time.
  • When you want to clearly display relationships with continuous data.

Basic Line Chart

#Lets use the APPL dataset and see the stock price over time
import pandas as pd
import plotly.graph_objects as go
from plotly.offline import init_notebook_mode, plot
from IPython.core.display import display, HTML
init_notebook_mode(connected=True)

#Hopefully you remeber how to import text files
APPL = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_apple_stock.csv')

fig = go.Figure(data=go.Scatter(x=APPL.AAPL_x, y=APPL.AAPL_y, #You can also call columns like methods (i.e. after the period)
                                mode='lines')) 
plot(fig, filename = 'figure8-4-1.html')
display(HTML('figure8-4-1.html'))

Multiple Line Chart (adding traces)

#Lets add some more stocks
Stocks = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/stockdata2.csv')
Stocks['Date'] = pd.to_datetime(Stocks['Date'])

Stocks_pivot = Stocks.pivot_table(index=['Date'],columns =['stock'],values=['value']) #Pivoting to have each stack as a column
Stocks_pivot = pd.DataFrame(Stocks_pivot.to_records()) #Pivot table to a dataframe
Stocks_pivot.columns = ['Date', 'AAPL', 'GSPC', 'IBM', 'MSFT', 'SBUX'] # renaming all columns

#Very Similar to making a scatter plot
fig = go.Figure()

# Add traces for each scatter
fig.add_trace(go.Scatter(x=Stocks_pivot['Date'], y=Stocks_pivot['AAPL'],
                    mode='lines',
                    name='APPL',
                    line=dict(color='#A3AAAE', width=2)))
fig.add_trace(go.Scatter(x=Stocks_pivot['Date'], y=Stocks_pivot['IBM'],
                    mode='lines',
                    name='IBM',
                    line=dict(color='#054ada', width=2)))
fig.add_trace(go.Scatter(x=Stocks_pivot['Date'], y=Stocks_pivot['MSFT'],
                    mode='lines',
                    name='MSFT',
                    line=dict(color='#F25022', width=2)))
fig.add_trace(go.Scatter(x=Stocks_pivot['Date'], y=Stocks_pivot['SBUX'],
                    mode='lines',
                    name='SBUX',
                    line=dict(color='#00704A', width=2)))


# Set options common to all traces (i.e title, background color)
fig.update_layout(title='Stocks (2007-2016)',
                  plot_bgcolor = 'white')

plot(fig, filename = 'figure8-4-2.html')
display(HTML('figure8-4-2.html'))